﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;

namespace DemoMidiDuSkill.Tools
{
    public static class MyPlaceUIElementExtension
    {
        /// <summary>
        /// Get a renderTransform property from transform group
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pUIElement"></param>
        /// <param name="pOccurenceIndex"></param>
        /// <returns></returns>
        public static T GetTransform<T>(this UIElement pUIElement, Int32 pOccurenceIndex)
            where T : Transform
        {
            return (pUIElement.RenderTransform as TransformGroup) != null
                ? (pUIElement.RenderTransform as TransformGroup).Children
                    .OfType<T>().ElementAtOrDefault(pOccurenceIndex) 
                : null;
        }


        /// <summary>
        /// Get a renderTransform property from transform group
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pUIElement"></param>
        /// <returns></returns>
        public static T GetTransform<T>(this UIElement pUIElement)
            where T : Transform
        {
            return GetTransform<T>(pUIElement, 0);
        }

        public static Point Diff(this UIElement pUIElement1, UIElement pUIElement2)
        {
            if (pUIElement1 != null && pUIElement2 != null)
            {
                Point vPoint1 = pUIElement1.TransformToVisual(Application.Current.RootVisual).Transform(new Point());
                Point vPoint2 = pUIElement2.TransformToVisual(Application.Current.RootVisual).Transform(new Point());
                return new Point(vPoint1.X - vPoint2.X, vPoint1.Y - vPoint2.Y);
            }

            return default(Point);
        }

        public static Double DistSquare(this UIElement pUIElement1, UIElement pUIElement2)
        {
            Point vDiff = pUIElement1.Diff(pUIElement2);
            return Math.Pow(vDiff.X, 2) + Math.Pow(vDiff.Y, 2);
        }

        public static Double Dist(this UIElement pUIElement1, UIElement pUIElement2)
        {
            return Math.Sqrt(pUIElement1.DistSquare(pUIElement2));
        }
    }
}
